<template>
  <a-modal
    :width="750"
    :visible="visible"
    :title="params.name"
    @ok="handleOk"
    @cancel="handleClose"
    centered
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="in" tab="淡入"></a-tab-pane>
      <a-tab-pane key="out" tab="淡出"></a-tab-pane>
    </a-tabs>

    <div class="operate_con">
      <div class="left_con">
        <span>随机转场：</span>
        <a-switch
          v-if="activeKey === 'in'"
          v-model:checked="filterForm.randomIn"
        />
        <a-switch
          v-if="activeKey === 'out'"
          v-model:checked="filterForm.randomOut"
        />
      </div>
    </div>

    <div class="form_con">
      <div class="form_item">
        <div class="form_title">自选转场</div>
        <div class="form_desc">将随机选用已选择的转场</div>
        <div class="selected-transition-con">
          <a-tag
            v-for="(item, index) in selectedTransitionList[activeKey]"
            closable
            color="error"
            @close.prevent="() => handleCancelSelect(index)"
          >
            {{ JSON.parse(item)?.material_name }}</a-tag
          >
        </div>
      </div>
    </div>

    <div class="form_con" style="height: 360px">
      <a-checkbox-group v-model:value="selectedTransitionList[activeKey]">
        <div
          class="form_item"
          v-for="(item, index) in transitionList[activeKey]"
          :key="index"
        >
          <div class="form_title">{{ item.name }}</div>
          <div class="filter_con">
            <div
              class="filter_item"
              :class="
                (filterForm.randomIn && activeKey === 'in') ||
                (filterForm.randomOut && activeKey === 'out')
                  ? 'filter-item-disabled'
                  : ''
              "
              v-for="(transition_item, transition_index) in item.materials"
              :key="transition_index"
            >
              <label>
                <a-checkbox
                  :disabled="
                    (filterForm.randomIn && activeKey === 'in') ||
                    (filterForm.randomOut && activeKey === 'out')
                  "
                  v-show="
                    !(
                      (filterForm.randomIn && activeKey === 'in') ||
                      (filterForm.randomOut && activeKey === 'out')
                    )
                  "
                  class="filter-checkbox"
                  :value="JSON.stringify(transition_item)"
                >
                </a-checkbox>

                <div class="filter_img">
                  <video
                    class="video"
                    @mouseenter="handleMouseEnter"
                    :controls="false"
                    :src="transition_item.material_url"
                  ></video>
                </div>
                <div class="filter_name">
                  {{ transition_item.material_name }}
                </div>
              </label>
            </div>
          </div>
        </div>
      </a-checkbox-group>
    </div>

    <template #footer>
      <a-button @click="handleClose">取消</a-button>
      <a-button @click="handleOk" type="primary" style="margin-left: 10px"
        >保存</a-button
      >
    </template>
  </a-modal>
</template>

<script>
import request from "../../../../../../common/utils/request";
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  createVNode,
  ref,
  nextTick,
} from "vue";
import {
  FolderAddOutlined,
  MinusOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import store from "../../../../../../store";

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: () => {
        return {};
      },
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
  },

  components: {},

  setup(props, context) {
    const state = reactive({
      filterForm: {
        randomIn: false,
        randomOut: false,
      },
      selectedTransitionList: {
        in: [],
        out: [],
      },
      transitionList: {
        in: [],
        out: [],
      },
      activeKey: "in",
    });

    watch(
      () => state.filterForm.randomIn,
      (val) => {
        if (val) {
          state.selectedTransitionList.in = [];
        }
      }
    );
    watch(
      () => state.filterForm.randomOut,
      (val) => {
        if (val) {
          state.selectedTransitionList.out = [];
        }
      }
    );

    const handleOk = () => {
      const dataIn = {
        random: state.filterForm.randomIn,
        transition: "in",
        sub_types: state.selectedTransitionList.in.map((item) =>
          JSON.parse(item)
        ),
      };
      const dataOut = {
        random: state.filterForm.randomOut,
        transition: "out",
        sub_types: state.selectedTransitionList.out.map((item) =>
          JSON.parse(item)
        ),
      };

      let transitions = {};
      const transitionData = store.getters.clipJSON?.effects?.find(
        (item) => item.type === "transitions"
      );

      if (!transitionData) {
        transitions = {
          type: "transitions",
          params: [
            ...Array.from({ length: props.currentIndex }, () => [
              {
                random: false,
                transition: "in",
                sub_types: [],
              },
              {
                random: false,
                transition: "out",
                sub_types: [],
              },
            ]),
            [dataIn, dataOut],
          ],
        };
      } else {
        transitions = JSON.parse(JSON.stringify(transitionData));
        for (let index = 0; index <= props.currentIndex; index++) {
          if (!transitions.params[index]) {
            transitions.params[index] = [
              {
                random: false,
                transition: "in",
                sub_types: [],
              },
              {
                random: false,
                transition: "out",
                sub_types: [],
              },
            ];
          }
        }
        transitions.params[props.currentIndex] = [dataIn, dataOut];
      }

      store.dispatch("SetClipJSONEffects", transitions);
      context.emit("close");
    };

    const handleClose = () => {
      context.emit("close");
    };

    const handleCancelSelect = (index) => {
      state.selectedTransitionList[state.activeKey].splice(index, 1);
    };

    const getTransitionList = () => {
      request
        .get("/work_ai", "/user/shotstack/material/transtions/list")
        .then((res) => {
          state.transitionList.in = res.result?.transitions_in;
          state.transitionList.in.forEach((it) => {
            it?.materials?.forEach((item) => {
              const findIndex = state.selectedTransitionList.in.findIndex(
                (i) => JSON.parse(i).id === item.id
              );
              if (findIndex > -1) {
                state.selectedTransitionList.in[findIndex] =
                  JSON.stringify(item);
              }
            });
          });
          state.transitionList.out = res.result?.transitions_out;
          state.transitionList.out?.forEach((it) => {
            it?.materials?.forEach((item) => {
              const findIndex = state.selectedTransitionList.out.findIndex(
                (i) => JSON.parse(i).id === item.id
              );
              if (findIndex > -1) {
                state.selectedTransitionList.out[findIndex] =
                  JSON.stringify(item);
              }
            });
          });
        });
    };

    const handleMouseEnter = (e) => {
      e.target.currentTime = 0;
      e.target?.play();
    };

    watch(
      () => props.visible,
      (val) => {
        const { data } = props;

        if (val) {
          state.activeKey = "in";
          state.filterForm.randomIn = data?.[0]?.random || false;
          state.filterForm.randomOut = data?.[1]?.random || false;
          state.selectedTransitionList["in"] =
            data?.[0]?.sub_types?.map((item) => JSON.stringify(item)) || [];
          state.selectedTransitionList["out"] =
            data?.[1]?.sub_types?.map((item) => JSON.stringify(item)) || [];

          getTransitionList();
        }
      }
    );

    return {
      ...toRefs(state),
      handleOk,
      handleClose,
      getTransitionList,
      handleCancelSelect,
      handleMouseEnter,
    };
  },
});
</script>

<style lang="less" scoped>
.operate_con {
  display: flex;
  align-items: center;

  .left_con {
    display: flex;
    align-items: center;
  }

  .right_con {
    display: flex;
    align-items: center;
    margin-left: 100px;
  }
}

.form_con {
  overflow-y: scroll;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  .form_item {
    margin-top: 10px;

    .form_title {
      color: #333;
      font-weight: bold;
      font-size: 14px;
    }

    .form_desc {
      color: #999;
      font-size: 12px;
    }

    .selected-transition-con {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-items: center;
      margin: 10px 0;
      & > span {
        margin-right: 20px;
        margin-bottom: 10px;
      }
    }

    .filter_con {
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;
      transform: translateX(-10px);

      .filter_item {
        position: relative;
        margin-left: 10px;
        margin-top: 10px;
        width: 106px;
        display: flex;
        flex-direction: column;
        cursor: pointer;

        &:hover {
          &::before {
            display: none;
          }
        }

        &::before {
          width: 106px;
          height: 60px;
          border-radius: 4px;
          background-image: url("../image/transition-poster.png");
          background-size: contain;
          position: absolute;
          left: 0;
          top: 0;
          opacity: 1;
          transition: opacity 0.2s ease-in-out;
          pointer-events: none;
          z-index: 10;
          content: "";
        }

        &.filter-item-disabled {
          &::before {
            filter: grayscale(0.5);
          }
          .filter_img video {
            filter: grayscale(0.5);
          }
          .filter_name {
            filter: grayscale(0.5);
          }
        }

        .filter-checkbox {
          position: absolute;
          right: 5px;
          top: 0;
          z-index: 11;
          cursor: pointer;
          pointer-events: none;
        }

        .filter_img video {
          width: 100%;
          height: 60px;
          border-radius: 4px;
          cursor: pointer;
          object-fit: contain;
          overflow-clip-margin: content-box;
          overflow: clip;
        }

        .filter_name {
          color: #666;
          margin-top: 5px;
        }
      }
    }
  }
}
</style>
